﻿using System.Linq;
using System.Web;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Eneta.Portal.Common;

namespace Eneta.Portal.Companies.Handlers
{
    public class IoTooltipHandler : IHttpHandler
    {
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var request = context.Request;
            var l3ID = request.QueryString["l3"];

            var repository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);
            var levels = repository.GetIoLevels();

            var products = from l in levels
                         from l2 in l.Level2Items
                         from l3 in l2.Level3Items
                         from p in l3.Products 
                         where l3.Id.ToString() == l3ID
                         select p.Title;
            
            var count = products.Count();

            var productString = "";
            if (count == 0)
                productString += Resources.GetResourceString("RequiredMainProductsMissing");
            else if (count == 1)
                productString += Resources.GetResourceString("RequiredMainProductLabel") + " ";
            else if (count > 1)
                productString += Resources.GetResourceString("RequiredMainProductsLabel") + " ";

            if(count > 0)
                productString += string.Join(" / ", products.ToArray());
            var response = context.Response;

            response.ClearHeaders();
            response.Clear();

            response.ContentType = "text/html";
            response.Write("<p>");
            response.Write(productString);
            response.Write("</p>");

            response.Flush();
            response.End();
        }
    }
}
